<?php
/**
 * Created by PhpStorm.
 * User: zhanglihe
 * Date: 2018/6/4
 * Time: 上午10:30
 */

namespace Modules\Token\Driver;

use Illuminate\Support\Facades\DB;

class StorageDB implements StorageInterface
{
    /**
     * 存放token表名
     *
     * @var
     */
    protected $table;

    /**
     * 有效时间（分钟）
     *
     * @var
     */
    protected $minutes;

    public function __construct($options)
    {
        $this->table   = $options['table'];
        $this->minutes = $options['minutes'];
    }

    public function has($key)
    {
        return DB::table($this->table)->where('token', $key)->count() ? true : false;
    }

    public function put($key, Array $data)
    {
        DB::table($this->table)->insert([
            'token'      => $key,
            'data'       => json_encode($data),
            'created_at' => date('Y-m-d H:i:s'),
            'expired_at' => date('Y-m-d H:i:s', time() + ($this->minutes * 60)),
        ]);
    }

    public function get($key)
    {
        $data = DB::table($this->table)->select(['token', 'data'])->where('token', $key)->first();
        if (!$data) {
            return null;
        }

        //$data = $data->toArray();
        $data = json_decode(json_encode($data),true);
        if ($data['data']) {
            $data['data'] = json_decode($data['data'],true);
        }
        return $data['data'];
    }

    public function forget($key)
    {
        DB::table($this->table)->where('token', $key)->delete();
    }

    public function flushExpired()
    {
        DB::table($this->table)->where('expired_at', '<', date('Y-m-d H:i:s'))->delete();
    }
}